﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Newtonsoft.Json;
using Zhp.Model.Common;

namespace Zhp.Api.Filters
{
    public class ApiResultFilter : IAlwaysRunResultFilter
    {
        public void OnResultExecuting(ResultExecutingContext context)
        {
            //if (context.Result is ChallengeResult)
            //{
            //    return;
            //}
            //if (context.Result is ForbidResult)
            //{
            //    return;
            //}
            //if (context.Result is JsonResult)
            //{
            //    return;
            //}
            //if (context.Result is FileResult)
            //{
            //    return;
            //}
            if (context.Result is EmptyResult)
            {
                context.Result = new JsonResult(new { StatusCode = StatusCodes.Status200OK, Value = "操作成功！" });
            }
            else if (context.HttpContext.Request.Headers["workflow"].ToString() == "true" || context.HttpContext.Request.Path == "/api/workflow/index")
            {
                return;
            }
            else if (context.Result is ObjectResult && context.HttpContext.Request.Path.Value.StartsWith("/api"))
            {
                var result = context.Result as ObjectResult;
                var body = result?.Value;
                if (body is bool)
                {
                    bool success = (bool)body;
                    var ret = new BaseRet()
                    {
                        Success = success,
                        Message = success == false ? "操作失败！" : "操作成功！"
                    };

                    body = ret;
                }

                int status = result?.StatusCode == null ? StatusCodes.Status200OK : result.StatusCode.Value;

                string message = status == StatusCodes.Status200OK ? "操作成功！" : JsonConvert.SerializeObject(body);

                var apiResult = new ApiResult
                {
                    Status = status,
                    Body = body,
                    Message = message,
                    Url = context.HttpContext.Request.Path,
                };

                context.Result = new JsonResult(apiResult);
            }
            else
            {
                return;
            }
        }
        
        public void OnResultExecuted(ResultExecutedContext context)
        {

        }

    }
}
